package com.zhan.rkforum.controller;

import com.zhan.rkforum.annotation.LoginRequired;
import com.zhan.rkforum.bean.User;
import com.zhan.rkforum.service.FollowService;
import com.zhan.rkforum.service.LikeService;
import com.zhan.rkforum.service.UserService;
import com.zhan.rkforum.util.CommunityConstant;
import com.zhan.rkforum.util.CommunityUtil;
import com.zhan.rkforum.util.HostHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.util.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;


@Controller
@RequestMapping(value = "/user")
public class UserController implements CommunityConstant {

    private final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @Value("${community.path.address}")
    private String address;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Value("${community.path.uploadPath}")
    private String uploadPath;

    @Autowired
    private HostHolder holder;

    @Autowired
    private LikeService likeService;

    @Autowired
    private FollowService followService;


    @LoginRequired
    @GetMapping(value = "/setting")
    public String toSetting(){
        return "site/setting";
    }

    @PostMapping("/upload")
    public String upload(MultipartFile headerImage, Model model){
        if(! headerImage.isEmpty()){
            String filename = headerImage.getOriginalFilename();
            assert filename != null;//断言 filename不为空
            String suffix = filename.substring(filename.lastIndexOf("."));
            filename = CommunityUtil.generateUuid() + suffix;
            File file = new File(uploadPath + "/" + filename);
            try {
                headerImage.transferTo(file);
            } catch (IOException e) {
                logger.error("文件上传失败： " + e.getMessage());
            }
            String headerUrl = address + contextPath + "/user/header/" +filename;
            User user = holder.getUser();
            userService.updateHeader(user.getId(),headerUrl);
            return "redirect:/index";
        }
        model.addAttribute("errorMsg","请选择上传文件");
        return "site/setting";
    }

    @GetMapping("/header/{filename}")
    public void getHeaderUrl(@PathVariable("filename")String filename, HttpServletResponse response){
        //D:/work/java/IdeaProject/rkforum/upload
        filename = uploadPath + "/" + filename;
        String suffix = filename.substring(filename.lastIndexOf("."));
        response.setContentType("image/" + suffix);//设置输出文件格式
        try (
            FileInputStream fis = new FileInputStream(filename);
            ServletOutputStream os = response.getOutputStream();
            ) {
                byte[] b = new byte[1024];
                int len = 0;
                while ((len = fis.read(b)) != -1){
                    os.write(b, 0, len);
                }
            } catch (IOException e) {
                logger.error("头像读取失败：" + e.getMessage());
            }
    }

    @LoginRequired
    @PostMapping("/updatePassword")
    public String updatePassword(String oldPassword, String newPassword, Model model){
        if(StringUtils.isEmpty(oldPassword)){
            model.addAttribute("oldPasswordErrorMsg","请输入原始密码");
            return "site/setting";
        }
        if (StringUtils.isEmpty(newPassword)){
            model.addAttribute("newPasswordErrorMsg","请输入新密码");
            return "site/setting";
        }

        User user = holder.getUser();
        String s = CommunityUtil.parseByMd5(oldPassword, user.getSalt());
        if(user.getPassword().equals(s)){
            newPassword = CommunityUtil.parseByMd5(newPassword, user.getSalt());
            userService.updatePassword(user.getId(), newPassword);
            user.setPassword(newPassword);
            holder.clear();
            holder.setUser(user);
            model.addAttribute("passwordMsg","密码修改成功！");
            return "site/setting";
        }else {
            model.addAttribute("newPasswordErrorMsg","原密码错误，请重新输入");
            return "site/setting";
        }
    }

    @GetMapping("/profile/{userId}")
    public String profileDetail(@PathVariable("userId") int userId, Model model){
        User user = userService.findUserById(userId);
        int userLikeCount = likeService.getUserLikeCount(userId);
        model.addAttribute("userLikeCount", userLikeCount);
        Long followeeCount = followService.getFolloweeCount(ENTITY_TYPE_USER, userId);
        model.addAttribute("followeeCount", followeeCount);
        Long followerCount = followService.getFollowerCount(ENTITY_TYPE_USER, userId);
        model.addAttribute("followerCount", followerCount);
        model.addAttribute("user", user);
        boolean hasFollowed = false;
        if(holder.getUser() != null){
            hasFollowed = followService.hasFollowed(ENTITY_TYPE_USER, userId,holder.getUser().getId());
        }
        model.addAttribute("hasFollowed",hasFollowed);
        return "site/profile";
    }




}
